package com.tansuo365.test1.controller.othercontrol;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tansuo365.test1.bean.otherbean.YanshouDetails;
import com.tansuo365.test1.bean.otherbean.YanshouZong;
import com.tansuo365.test1.service.kucunservice.WuliaoKucunRiZhiService;
import com.tansuo365.test1.service.otherservice.YanshouDetailsService;
import com.tansuo365.test1.service.otherservice.YanshouZongService;
import com.tansuo365.test1.util.DateUtil;
import com.tansuo365.test1.util.StringUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PropertySource(value = "classpath:danhao.properties")
@Api(value = "验收单相关控制层", tags = "", description = "")
@RestController
@RequestMapping("/admin/yanshoudan")
public class YanshouDanController {

    @Autowired
    private YanshouZongService yanshouZongService;
    @Autowired
    private YanshouDetailsService yanshouDetailsService;

    @Value("${danhao.yanshoudan.prefix}")
    private String yanshoudanPrefix;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }

    /**
     * 获取yanshou单号
     *
     * @param type
     * @return
     * @throws Exception
     */
    @Async
    @RequestMapping("/getYanshouNumber")
    public ListenableFuture<String> genBillCode(String type) throws Exception {
        StringBuffer billCodeStr = new StringBuffer();
        billCodeStr.append(yanshoudanPrefix);
        billCodeStr.append(DateUtil.getCurrentDateStr());
        String todayMaxYanshouDanNumber = yanshouZongService.getTodayMaxYanshouDanNumber();
        if (todayMaxYanshouDanNumber != null) {
            billCodeStr.append(StringUtil.formatCode(todayMaxYanshouDanNumber));
        } else {
            billCodeStr.append("0001");
        }
        return new AsyncResult<>(billCodeStr.toString());
    }

    @RequestMapping("/getSelective")
    public Map<String, Object> getYanshoudan(YanshouZong yanshouZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (yanshouZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<YanshouZong> yanshouZongsList = yanshouZongService.listYanshouZong(yanshouZong);
        PageInfo<YanshouZong> pageInfo = new PageInfo<YanshouZong>(yanshouZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    /**
     * 根据zongzhang总表的id查询对应的子表数据 分页
     *
     * @param page
     * @param rows
     * @return 根据总表id遍历查询详细的物料集合
     */
    @RequestMapping("/listDetailsByZId")
    public Map<String, Object> listDetailsByZongId(YanshouDetails yanshouDetails, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (yanshouDetails == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<YanshouDetails> yanshouDetailsList = yanshouDetailsService.listYanshouDetailsSelective(yanshouDetails);
        PageInfo<YanshouDetails> pageInfo = new PageInfo<YanshouDetails>(yanshouDetailsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    /**
     * 保存验收总表+子表数据 OK
     *
     * @return
     */
    @RequestMapping("/save")
    public Map<String, Object> save(HttpSession session, YanshouZong yanshouZong, @RequestParam("wuliaoYanshouDetailsJson") String wuliaoYanshouDetailsJson) {
        if (yanshouZong == null || wuliaoYanshouDetailsJson == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        Gson gson = new Gson();
        List<YanshouDetails> yanshouDetailsList = gson.fromJson(wuliaoYanshouDetailsJson, new TypeToken<List<YanshouDetails>>() {
        }.getType());
        yanshouZong.setFounder((String) session.getAttribute("truename"));
        //save时,先保存大表,大表返回id后再保存附表
        int insertCode = yanshouZongService.saveZongAndDetails(yanshouZong, yanshouDetailsList);
        if (insertCode > 0) {
            resultMap.put("success", true);
            resultMap.put("msg", "保存成功");
        } else {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败");
        }
        return resultMap;
    }


    /**
     * 更新验收总表
     *
     * @return
     */
    @RequestMapping("/update")
    public Map<String, Object> update(YanshouZong yanshouZong) {
        if (yanshouZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        int updateCode = yanshouZongService.updateByPrimaryKeySelective(yanshouZong);
        if (updateCode > 0) {
            resultMap.put("success", true);
        } else {
            resultMap.put("success", false);
        }
        return resultMap;
    }

    /**
     * 删除  这里的删除同样删除了子表数据
     *
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    public Map<String, Object> deleteBatch(@RequestParam("ids[]") Integer[] ids) {
        Map<String, Object> resultMap = new HashMap<>();
        if (ids == null || ids.length == 0) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "请选中条目进行删除");
            return resultMap;
        }
        int ziDelCode = 0;
        int code = yanshouZongService.deleteBatchByPKArr(ids);  //批量删除主表
        if (code > 0) {
            ziDelCode = yanshouDetailsService.deleteByZongIdArr(ids); //批量删除详细根据ids条目
        }
        if (code > 0 && ziDelCode > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

}
